package com.nut.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nut.entity.Message;
import com.nut.entity.User;
import com.nut.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-04-15 16:13
 */

@Controller
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private UserService userService;

    /**
     * @Description 查询所有User
     * @param pn:分页数，第几页
     * @return 获取分页后的Json数据 (统一封装为Message对象)
     **/
    @ResponseBody
    @RequestMapping("/list")
    public Message getAllUsers(@RequestParam(value = "pn",defaultValue = "1")int pn)
    {
        //引入分页查询插件
        PageHelper.startPage(pn,5);
        List<User> userList = userService.findAll();

        PageInfo pageInfo = new PageInfo(userList,5);

        return Message.Success().payLoad("pageInfo",pageInfo);
    }

    /**
     * @Description User登录
     * @param userName: name
     * @param userPassword: password
     * @return 统一封装Message对象
     **/
    @ResponseBody
    @RequestMapping(value = "/login/{userName}/{userPassword}",method = RequestMethod.GET)
    public Message login(@PathVariable("userName")String userName,@PathVariable("userPassword")String userPassword)
    {
        User user = new User();
        user.setName(userName);
        user.setPassword(userPassword);

        User login = userService.login(user);
        if(login != null)
        {
            return Message.Success().payLoad("login_user",login);
        }
        else
        {
            return Message.Fail().payLoad("login_user",null);
        }
    }



    /**
     * @Description 新增员工
     * @param user:提交的User对象
     * @return 统一封装Message对象
     **/
    @ResponseBody
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Message saveUser(@Valid User user, BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            Map<String,Object> map = new HashMap<>();
            //后台JSR303数据校验失败
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors)
            {
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Message.Fail().payLoad("errorFields",map);
        }

        userService.saveUser(user);
        return Message.Success();
    }

    /**
     * @Description 校验User是否name重复
     * @param name: 前台传递的name
     * @return 统一封装Message对象
     **/
    @ResponseBody
    @RequestMapping("/checkUserName")
    public Message checkUserByName(@RequestParam(value = "name") String name)
    {
        //后台验证数据格式
        String nameRegExp = "(^[a-zA-Z-0-9_-]{1,6}$)";
        if(!name.matches(nameRegExp))
        {
            return Message.Fail().payLoad("va_msg","用户名数据格式错误");
        }
        boolean isRepeated = userService.checkUserByName(name);

        if(!isRepeated)
        {
            return Message.Success();
        }
        else
        {
            return Message.Fail().payLoad("va_msg","用户名重复");
        }
    }

    /**
     * @Description 根据id获取User
     * @param number:id
     * @return 统一封装后的Message
     **/
    @ResponseBody
    @RequestMapping(value = "/getUserById/{number}",method = RequestMethod.GET)
    public Message getUserById(@PathVariable("number")int number)
    {
        User user = userService.getUserById(number);
        return Message.Success().payLoad("user",user);
    }

    /**
     * @Description 保存修改后的User
     * @param user: 前台提交的User
     * @return 统一封装后的Message
     **/
    @ResponseBody
    @RequestMapping(value = "/save/{number}",method = RequestMethod.PUT)
    public Message saveUser(User user)
    {
        userService.updateUser(user);
        return Message.Success();
    }
    
    /**
     * @Description 根据id删除user,批量删除
     * @param numbers: 前台传递的ids
     * @return 统一封装后端的Message
     **/
    @ResponseBody
    @RequestMapping(value = "/delete/{numbers}",method = RequestMethod.DELETE)
    public Message deleteUser(@PathVariable("numbers")String numbers)
    {
        if(numbers.contains(","))
        {
            List<Integer> ids = new ArrayList<>();
            String[] split_ids = numbers.split(",");
            for (String split_id : split_ids)
            {
                ids.add(Integer.parseInt(split_id));
            }

            userService.batchDelete(ids);
        }
        else
        {
            int id = Integer.parseInt(numbers);
            userService.deleteUserById(id);
        }
        return Message.Success();
    }

    /**
     * @Description 转账业务
     * @param : jsons: Json数据
     * @return 统一封装后的Message对象
     **/
    @ResponseBody
    @RequestMapping(value = "/transfer",method = RequestMethod.PUT)
    public Message transfer(@RequestParam("jsons")String jsons)
    {
        List<User> userList = JSON.parseArray(jsons,User.class);
        User userA = userList.get(0);
        User userB = userList.get(1);

        //userA扣钱，userB加钱
        userService.transfer(userA,userB);

        return Message.Success();
    }
}
